var jsonobj1=""
var  resultiowk={};
var newdata=""
var oldstart=""
var inputmm=""
var inputid=""
var inputcode=""
var inputmsg=""
var modifyPriceWays=""
var customerTypes=""
var dataall=""
var inputcodes=""
var reall=""
//导入商品
//进入页面渲染


var customerids=sessionStorage.getItem("customerid")
aa()
$("#c").attr("disabled", true)//签约价置灰不能点击
function aa() {

    if(sessionStorage.getItem("click_a")==1){
        $("#a").attr("checked","checked");
    }
    if(sessionStorage.getItem("click_b")==1){
        $("#b").attr("checked","checked");
    }
    if(sessionStorage.getItem("zhekoulv")!=null)
    {
        document.getElementById('zhekou').value=sessionStorage.getItem("zhekoulv")
    }

    var oneCategoryIds=''
    var twoCategoryIds=''
    var threeCategoryIds=''
    if($("#class1").val()!='') {
        oneCategoryIds = oneCategoryId

    }else {
        oneCategoryIds = ''

    }
    if( $("#class2").val()!='') {

        twoCategoryIds = twoCategoryId

    }else {

        twoCategoryIds = ''

    }
    if($("#class3").val()!='') {

        threeCategoryIds = threeCategoryId
    }else {

        threeCategoryIds = ''
    }

    $.ajax({
        url:root.dockingplatform.getInfo,
        cache: false,  //禁用缓存
        type: "POST",
        dataType:'json',
        contentType: "application/json",
        data: JSON.stringify({
            pageNum:1,
            pageSize:2000000,
            "customerId":customerids,
            "basePriceType":$("input[name=radio1]:checked").val(),
            "customerUnifyCount":$("#zhekou").val(),
            "firstCategoryId":oneCategoryIds,
            "secondCategoryId":twoCategoryIds,
            "thirdCategoryId":threeCategoryIds,
            "brandName":$("#username").val().trim(),
            "spuCode":$("#spuCode").val().trim(),
            "skuName":$("#spuName").val().trim(),//商品名称
            "skuCode":$("#skuCode").val().trim(),
            "helpcode":$("#helpCode").val().trim(),//助记码
        }),
        success: function (result) {
            $("#quyu").html(result.data.areaName)
            if(result.data.customerPriceUnifyRuleDto!=null){

            $("#zhekou").val(result.data.customerPriceUnifyRuleDto.customerUnifyCount)
                reall=result.data.customerPriceUnifyRuleDto.basePriceType
            if(result.data.customerPriceUnifyRuleDto.basePriceType==1){
                $("#a").attr("checked","checked");
                $("#a").attr("disabled","disabled");
                $("#b").attr("disabled","disabled");
            }else if(result.data.customerPriceUnifyRuleDto.basePriceType==2){
                $("#b").attr("checked","checked");
                $("#b").attr("disabled","disabled");
                $("#a").attr("disabled","disabled");
            }else if(result.data.customerPriceUnifyRuleDto.basePriceType==3){
                $("#c").attr("checked","checked");
            }
            }
            perceshow()

        },
        error: function () {
            $.Huimodalalert('失败！',2000);
        }
    });
}
//切换基础价
function pricess() {
    var cu = layer.confirm('<span>变更基础价，可能会出现调价方式中存在低于成本价情况，请认真检查！务必点击“同步商品”！</span>', {title:'提示',closeBtn:false,btn: ['确认', '取消']}, function(index){
        pricess2()
        layer.close(cu);
    },function(){
        pppp()
        layer.close(cu);

    });
}
function pricess2() {
    perceshow()
}
function pppp() {
        $("#a").attr("checked",false);
        $("#b").attr("checked",false);
        $("#c").attr("checked",false);
}


//查询
function perceshow() {
    var oneCategoryIds=''
    var twoCategoryIds=''
    var threeCategoryIds=''
    if($("#class1").val()!='') {
        oneCategoryIds = oneCategoryId

    }else {
        oneCategoryIds = ''

    }
    if( $("#class2").val()!='') {

        twoCategoryIds = twoCategoryId

    }else {

        twoCategoryIds = ''

    }
    if($("#class3").val()!='') {

        threeCategoryIds = threeCategoryId
    }else {

        threeCategoryIds = ''
    }
   var zhekou=""
    if($("#zhekou").val()==""){
        zhekou="100"
    }else {
        zhekou=$("#zhekou").val()
    }
    $.ajax({
        url:root.dockingplatform.getInfo,
        cache: false,  //禁用缓存
        type: "POST",
        dataType:'json',
        contentType: "application/json",
        data: JSON.stringify({
            pageNum:1,
            pageSize:2000000,
            "customerId":customerids,
            "basePriceType":$("input[name=radio1]:checked").val(),
            "customerUnifyCount":zhekou,
            "firstCategoryId":oneCategoryIds,
            "secondCategoryId":twoCategoryIds,
            "thirdCategoryId":threeCategoryIds,
            "brandName":$("#username").val().trim(),
            "spuCode":$("#spuCode").val().trim(),
            "skuName":$("#spuName").val().trim(),//商品名称
            "skuCode":$("#skuCode").val().trim(),
            "helpcode":$("#helpCode").val().trim(),//助记码
        }),
        success: function (result) {
            detaiists(result.data.customerPriceInfoRuleDtoPagination.data);
            $('.M-box3').pagination({
                pageCount: result.data.customerPriceInfoRuleDtoPagination.totalPage,
                jump: true,
                coping: true,
                prevContent: '上页',
                nextContent: '下页',
                callback: function (api) {
                    $.ajax({
                        url: root.dockingplatform.getInfo,
                        cache: false,  //禁用缓存
                        type: "POST",
                        dataType:'json',
                        contentType: "application/json",
                        data: JSON.stringify({
                            pageNum:api.getCurrent(),
                            pageSize:2000000,
                            "customerId":customerids,
                            "basePriceType":$("input[name=radio1]:checked").val(),
                            "customerUnifyCount":zhekou,
                            "firstCategoryId":oneCategoryIds,
                            "secondCategoryId":twoCategoryIds,
                            "thirdCategoryId":threeCategoryIds,
                            "brandName":$("#username").val().trim(),
                            "spuCode":$("#spuCode").val().trim(),
                            "skuName":$("#spuName").val().trim(),//商品名称
                            "skuCode":$("#skuCode").val().trim(),
                            "helpcode":$("#helpCode").val().trim(),//助记码
                        }),

                        success: function (result) {
                            detaiists(result.data.customerPriceInfoRuleDtoPagination.data);
                            $("#spu_all").attr("checked", false);
                        },
                        error: function (XMLHttpRequest, textStatus, errorThrown) {
                            alert(XMLHttpRequest);
                        }
                    });
                }
            });

        },
        error: function () {
            $.Huimodalalert('失败！',2000);
        }
    });
}
var setTablsDatas;
/*表格渲染*/
var dataSource = new Array();
//table的数据源
var table;   //table对象
dataSource = [];

function detaiists(data) {
    console.log(data)
    newdata=data
    dataall=data
    dataSource.splice(0, dataSource.length);//清空数组

    $.each(data, function (i, field) {
        var rowData = new Array();
        rowData.push(field.firstCategoryName);
        rowData.push(field.secondCategoryName);
        rowData.push(field.thirdCategoryName);
        rowData.push(field.brandName);
        rowData.push(field.spuCode);
        rowData.push(field.spuName);
        rowData.push(field.skuCode);
        rowData.push(field.specifications);
        rowData.push(field.unit);
        rowData.push(field.modifyPriceWay);
        rowData.push(field.modifyPriceValue);
        rowData.push(field.id);
        rowData.push(field.isLowerCostPrice);
        dataSource.push(rowData);
    });
    initDataTable(dataSource);

    function initDataTable(dataSource) {
        if(data==""){
            $('.shun').html("")
            $("#datatable_paginate").hide()
        }else {

        var dttable = $('#datatable').dataTable(); // 初始化dataTable，清空上一个值
        dttable.fnClearTable(); //清空一下table
        dttable.fnDestroy(); //还原初始化了的datatable
        $("#datatable").DataTable({
            "autoWidth": false,
            "ordering": false,
            "searching": false,
            "paging": true,
            "retrieve": true,
            "destroy": true,
            "bAutoWidth": true,
            "bLengthChange": false,
            "aLengthMenu": [50],
            "oLanguage": {
                "sLengthMenu": "每页显示 _MENU_ 条记录",
                "sZeroRecords": "抱歉， 没有找到",
                "sInfo": "从 _START_ 到 _END_ /共 _TOTAL_ 条数据",
                "sInfoEmpty": "没有数据",
                "sInfoFiltered": "(从 _MAX_ 条数据中检索)",
                "oPaginate": {
                    "sFirst": "首页",
                    "sPrevious": "前一页",
                    "sNext": "后一页",
                    "sLast": "尾页"
                },
                "sZeroRecords": "没有检索到数据",
            },
            data: dataSource,
            columnDefs: [
                {
                    "visible": true,
                    "targets": 0
                },
                {
                    "render": function(data, type, row, meta) {
                        var val = '<span style="text-align: left;"><td><input class="spuId"  id="aaaa" type="checkbox" name="spuId" value = "' + row[11] + '">' + row[0] + '</td></span>';
                        return val;
                    },
                    "targets": 0
                },
                {
                    "render": function(data, type, row, meta) {
                        var val = '';

                        if(row[12]==true){


                        if (row[9] == 10 && (row[6] == null || row[6] == '')) {
                            var val = '<span style="display: inline-block;width: 210px; margin-top: 23px;"><td ><select class="select radius w-100 va-m" style="height:26px" onchange="jine(this)"><option value="10" >折扣率</option></select></td><td><input   style="width: 50px;" type="text" value="'+row[10]+'"><span style="display: inline-block;">%</span></td>&nbsp;<td><a class="" onclick="Cloes(\''+row[9]+'\',\''+row[11]+'\',\''+row[6]+'\',this)">修改</a></td></span><br><span style="color: #b94a48;margin-left: -106px;">低于成本价</span>';
                        }else if (row[9] == 10 && row[6] != null) {
                            var val = '<span style="display: inline-block;width: 210px;margin-top: 23px;"><td ><select class="select radius w-100 va-m" style="height:26px" onchange="jine(this)"><option value="10">折扣率</option><option value="20" >金额上调</option><option value="30">金额下调</option><option value="40">按价格</option></select></td><td><input   style="width: 50px;" type="text" value="'+row[10]+'"><span style="display: inline-block;">%</span></td>&nbsp;<td><a class="" onclick="Cloes(\''+row[9]+'\',\''+row[11]+'\',\''+row[6]+'\',this)">修改</a></td></span><br><span style="color: #b94a48;margin-left: -106px;">低于成本价</span>';
                        } else if (row[9] == 20) {
                            var val = '<span style="display: inline-block;width: 210px;margin-top: 23px;"><td><select class="select radius w-100 va-m" style="height:26px" onchange="jine(this)"><option value="10">折扣率</option><option value="20" selected>金额上调</option><option value="30">金额下调</option><option value="40">按价格</option></select></td><td><input   style="width: 50px;" type="text" value="'+row[10]+'"><span  style="display: none">%</span></td><td>&nbsp;<a class="" onclick="Cloes(\''+row[9]+'\',\''+row[11]+'\',\''+row[6]+'\',this)">修改</a></td></span><br><span style="color: #b94a48;margin-left: -106px;">低于成本价</span>';
                        } else if (row[9] == 30) {
                            var val = '<span style="display: inline-block;width: 210px;margin-top: 23px;"><td><select class="select radius w-100 va-m" style="height:26px" onchange="jine(this)"><option value="10">折扣率</option><option value="20">金额上调</option><option value="30" selected>金额下调</option><option value="40">按价格</option></select></td><td><input  style="width: 50px;" type="text" value="'+row[10]+'"><span  style="display: none">%</span></td><td>&nbsp;<a class="" onclick="Cloes(\''+row[9]+'\',\''+row[11]+'\',\''+row[6]+'\',this)">修改</a></td></span><br><span style="color: #b94a48;margin-left: -106px;">低于成本价</span>';
                        }else if (row[9] == 40) {
                            var val = '<span style="display: inline-block;width: 210px;margin-top: 23px;"><td><select class="select radius w-100 va-m" style="height:26px" onchange="jine(this)"><option value="10">折扣率</option><option value="20">金额上调</option><option value="30" >金额下调</option><option value="40" selected>按价格</option></select></td><td><input  style="width: 50px;" type="text" value="'+row[10]+'"><span  style="display: none">%</span></td><td>&nbsp;<a class="" onclick="Cloes(\''+row[9]+'\',\''+row[11]+'\',\''+row[6]+'\',this)">修改</a></td></span><br><span style="color: #b94a48;margin-left: -106px;">低于成本价</span>';
                        }
                        }else {
                            if (row[9] == 10 && (row[6] == null || row[6] == '')) {
                                var val = '<span style="display: inline-block;width: 210px;"><td ><select class="select radius w-100 va-m" style="height:26px" onchange="jine(this)"><option value="10" >折扣率</option></select></td><td><input   style="width: 50px;" type="text" value="'+row[10]+'"><span style="display: inline-block;">%</span></td>&nbsp;<td><a class="" onclick="Cloes(\''+row[9]+'\',\''+row[11]+'\',\''+row[6]+'\',this)">修改</a></td></span>';
                            }else if (row[9] == 10 && row[6] != null) {
                                var val = '<span style="display: inline-block;width: 210px;"><td ><select class="select radius w-100 va-m" style="height:26px" onchange="jine(this)"><option value="10">折扣率</option><option value="20" >金额上调</option><option value="30">金额下调</option><option value="40">按价格</option></select></td><td><input   style="width: 50px;" type="text" value="'+row[10]+'"><span style="display: inline-block;">%</span></td>&nbsp;<td><a class="" onclick="Cloes(\''+row[9]+'\',\''+row[11]+'\',\''+row[6]+'\',this)">修改</a></td></span>';
                            } else if (row[9] == 20) {
                                var val = '<span style="display: inline-block;width: 210px;"><td><select class="select radius w-100 va-m" style="height:26px" onchange="jine(this)"><option value="10">折扣率</option><option value="20" selected>金额上调</option><option value="30">金额下调</option><option value="40">按价格</option></select></td><td><input   style="width: 50px;" type="text" value="'+row[10]+'"><span  style="display: none">%</span></td><td>&nbsp;<a class="" onclick="Cloes(\''+row[9]+'\',\''+row[11]+'\',\''+row[6]+'\',this)">修改</a></td></span>';
                            } else if (row[9] == 30) {
                                var val = '<span style="display: inline-block;width: 210px;"><td><select class="select radius w-100 va-m" style="height:26px" onchange="jine(this)"><option value="10">折扣率</option><option value="20">金额上调</option><option value="30" selected>金额下调</option><option value="40">按价格</option></select></td><td><input  style="width: 50px;" type="text" value="'+row[10]+'"><span  style="display: none">%</span></td><td>&nbsp;<a class="" onclick="Cloes(\''+row[9]+'\',\''+row[11]+'\',\''+row[6]+'\',this)">修改</a></td></span><br>';
                            }else if (row[9] == 40) {
                                var val = '<span style="display: inline-block;width: 210px;"><td><select class="select radius w-100 va-m" style="height:26px" onchange="jine(this)"><option value="10">折扣率</option><option value="20">金额上调</option><option value="30" >金额下调</option><option value="40" selected>按价格</option></select></td><td><input  style="width: 50px;" type="text" value="'+row[10]+'"><span  style="display: none">%</span></td><td>&nbsp;<a class="" onclick="Cloes(\''+row[9]+'\',\''+row[11]+'\',\''+row[6]+'\',this)">修改</a></td></span><br>';
                            }
                        }
                        return val;
                    },
                    "targets": 9
                },
                {
                    "render": function (data, type, row) {
                        var val = '<span class=""><a onclick="detaildelete(\''+row[11]+'\',this)">删除</a></span>';
                        return val;
                    },
                    "targets": 10
                }
            ],
            "fnInitComplete": function(oSettings, json) {
                setBtnDis(0, $("#productManage"));
                $("#datatable").on("change", '.spuId', function() {
                    var num = $(".shun").find("input[type=checkbox]:checked").length;
                    setBtnDis(num, $("#productManage"));
                });

            }
        }); }
    };
}
//设置金额上下调金额默认为0
//设置金额上下调金额默认为0
function jine(el) {
    if(newdata.length>0){
        $.each(newdata,function(k,v){
            if($(el).parent().find('select').val()==20){
                $(el).parent().find('input').val(0)
                var spanEl = el.nextSibling.nextSibling;
                $(spanEl).css({
                    display: "none"
                });


            } else if($(el).parent().find('select').val()==30){
                $(el).parent().find('input').val(0)
                var spanElq = el.nextSibling.nextSibling;
                $(spanElq).css({
                    display: "none"
                });

            }else if($(el).parent().find('select').val()==10){
                $(el).parent().find('input').val(100)
                var spanEldf = el.nextSibling.nextSibling;
                $(spanEldf).css({
                    display: "inline-block"
                });


            }else if($(el).parent().find('select').val()==40){
                $(el).parent().find('input').val(0)
                var spanElq = el.nextSibling.nextSibling;
                $(spanElq).css({
                    display: "none"
                });

            }

        });
    }


}
//一级二级三级
function goodslistCategory(categoryLevel) {
    console.log($("#class1").val())
    var categoryName = $("#class1").val();
    var user_data = {
        categoryLevel: categoryLevel,
        categoryName: $("#class1").val(),
    }
    var succCallBack = function(data, status, response) {
        console.log("一级")
        console.log(data)
        if(data.errorCode == "0") {
            if(data.data == null) {
                classStr = "<li>无数据</li>"
                $("#classUl1").html(classStr);
            } else {
                var classStr = "";
                for(var i = 0; i < data.data.length; i++) {
                    classStr += "<li onclick='nextClass(" + data.data[i].category_id + "," + data.data[i].category_level + ",\"" + data.data[i].category_name + "\")'>" + data.data[i].category_name + "</li>"
                }
                $("#classUl1").html(classStr);
            }
        }
    }
    web.doAjax(root.goodsInter.categoryByParam, 'post', user_data, succCallBack);
}

//获取光标
$("#class1").focus(function() {
    $("#classUl1").show();
    goodslistCategory(1);
});
$(document).bind("click", function(e) {
    //id为menu的是菜单，id为open的是打开菜单的按钮
    if($(e.target).closest("#classUl1").length == 0 && $(e.target).closest("#class1").length == 0) {
        //点击id为menu之外且id不是不是open，则触发
        $("#classUl1").hide()
        $("#class2").val();

    }
});
var oneCategoryId = "";
var twoCategoryId = "";
var threeCategoryId = "";
var goodslist_cantegory_id; //定义分类搜索条件
// 2,3,4级的模糊查询
function getNext_input(level, category_id) {
    console.log(category_id)
    if(level == 2) {
        console.log(category_id+'一级')
        oneCategoryId = category_id;
    } else if(level == 3) {
        console.log(category_id+'二级')
        twoCategoryId = category_id;
    } else if(level == 4) {
        console.log(category_id+'三级')
        threeCategoryId = category_id;
    }
    if(level == 4) {
        goodslist_cantegory_id = category_id;
    }
    if(level < 4) {
        console.log(level)
        $("#class" + level + "")[0].oninput = function() {
            var user_data = {
                parentCateId: category_id,
                categoryName: $("#class" + level + "").val()
            }
            var succCallBack = function(data, status, response) {
                console.log("二级")
                console.log(data)
                if(data.errorCode == 0) {
                    if(data.data == null) {
                        classStr = "<li>无数据</li>";
                    } else {
                        var classStr = "";
                        for(var i = 0; i < data.data.length; i++) {
                            classStr += "<li onclick='nextClass(" + data.data[i].category_id + "," + data.data[i].category_level + ",\"" + data.data[i].category_name + "\")'>" + data.data[i].category_name + "</li>"
                        }
                    }
                    if(data.data[0] == undefined) {
                        classValue = category_id;
                        var nextLevel = level + 1;
                        $("#classUl" + nextLevel + "").html(classStr);
                        $("#classUl" + level + "").hide();
                    } else {
                        var nextLevel = data.data[0].category_level;
                        $("#classUl" + nextLevel + "").html(classStr);
                        $("#classUl" + level + "").show();
                    }
                }
            }
            web.doAjax(root.goodsInter.categoryByParam, 'post', user_data, succCallBack);
        }
        //获取光标
        $("#class" + level + "").focus(function() {
            $("#classUl" + level + "").show();
        });
        $(document).bind("click", function(e) {
            //id为menu的是菜单，id为open的是打开菜单的按钮
            if($(e.target).closest("#classUl" + level + "").length == 0 && $(e.target).closest("#class" + level + "").length == 0) {
                //点击id为menu之外且id不是不是open，则触发
                $("#classUl" + level + "").hide()
            }
        });
    }

}

function nextClass(category_id, level, category_name) {
    $("#class" + level + "").val(category_name);
    if(level == 1) {
        $("#class2").val("");
        $("#class3").val("");
    } else if(level == 2) {
        $("#class3").val("");
    }
    var user_data = {
        parentCateId: category_id,
    }
    var succCallBack = function(data, status, response) {
        console.log(data)
        if(data.errorCode == "0") {
            if(data.data == null) {
                classStr = "<li>无数据</li>";
            } else {
                var classStr = "";
                for(var i = 0; i < data.data.length; i++) {
                    classStr += "<li onclick='nextClass(" + data.data[i].category_id + "," + data.data[i].category_level + ",\"" + data.data[i].category_name + "\")'>" + data.data[i].category_name + "</li>"
                }
            }
            if(data.data[0] == undefined) {
                classValue = category_id;
                var nextLevel = level + 1;
                $("#classUl" + nextLevel + "").html(classStr);
                $("#classUl" + level + "").hide();
            } else {
                var nextLevel = data.data[0].category_level;
                $("#classUl" + nextLevel + "").html(classStr);
                $("#classUl" + nextLevel + "").show();
                $("#classUl" + level + "").hide()
            }
        }
    }
    getNext_input(level + 1, category_id);
    web.doAjax(root.goodsInter.categoryByParam, 'post', user_data, succCallBack);
}
/*品牌选择*/
function myfFunction(){
     brandName = "";
     brandId = "";
    $.ajax({
        url: root.goodsInter.goods_getListBrand,
        cache: false,  //禁用缓存
        type: "POST",
        data: {
            brandName: $("#username").val().trim()
        },
        success: function (data) {
            console.log(data)
            var jsonObj =data.ListBrand;
            if(jsonObj==""){
                $("#tudfan").html("<li>无数据</li> ");
            }else {
                var optionstring = "";
                for (var  i= 0; i < jsonObj.length; i++) {
                    jsonobj1=jsonObj[i].brandId
                    brandIds=jsonObj[i].brandId
                    optionstring += "<li onclick='addCodeFun("+ jsonObj[i].brandId+ ",\""+jsonObj[i].brandName+ "\")'>"+jsonObj[i].brandName+ "</li>";
                }
                $("#tudfan").html(optionstring);
            }
        }
    });
}
//运营经理获取光标
$("#username").focus(function () {
    $("#tudfan").show()
});
$(document).bind("click",function(e){
    //id为menu的是菜单，id为open的是打开菜单的按钮
    if($(e.target).closest("#tudfan").length == 0 && $(e.target).closest("#username").length == 0){
        //点击id为menu之外且id不是不是open，则触发
        $("#tudfan").hide()
    }
})
var brandName = "";
var brandId = "";
function addCodeFun(id,brand_name) {
    $("#tudfan").hide();
    $("#username").val(brand_name)
    brandName = brand_name;
    brandId = id;
}
function brand_sure() {
    sessionStorage.setItem("brand_name",brandName);
    sessionStorage.setItem("brand_id",brandId);
    $("#selectInp").css({
        display:"none"
    });
    addBrandName();
}
//渲染品牌名称
function addBrandName() {
    if(sessionStorage.getItem("brand_name")){
        $("#brandName").html(sessionStorage.getItem("brand_name"));
        $("#brandId").html(sessionStorage.getItem("brand_id"));
    }
}
//渲染属性名称
function addAttrName() {
    console.log(sessionStorage.getItem("attrObjCanch")+"##########");
    if(sessionStorage.getItem("attrObjCanch")){
        var attrObjCanch = JSON.parse(sessionStorage.getItem("attrObjCanch"));
        for(var i=0;i<attrObjCanch.length;i++){
            var attrValStr="";
            var attrIdsStr="";
            if(attrObjCanch[i].value.length != 0){
                for(var j=0;j<attrObjCanch[i].value.length;j++){
                    attrValStr += attrObjCanch[i].value[j].attri_value+";";
                    attrIdsStr +=attrObjCanch[i].value[j].attri_value_id+";";
                }
            }
            $("#appendAttr").remove();
            $("#attrTable").append('<tr id = "appendAttr"><th class="col-6-1 text-c">'+attrObjCanch[i].attribute_name+'</th><td><span>'+attrValStr+'</span><a onclick="addAttr('+attrObjCanch[i].attribute_id+",'"+attrIdsStr+"'"+')">添加</a></td></tr>')
        }
    }
}
function stoprop() {
    /*批量上架全选框阻止冒泡*/
    var timer = setTimeout(function() {
        var num = $("#datatable").find("tbody").find("input[type=checkbox]:checked").length;
        setBtnDis(num, $("#productManage"));
        clearTimeout(timer);
    }, 200)

    window.event ? window.event.cancelBubble = true : e.stopPropagation();
}
function setBtnDis(num, pnode) { //如果选中项为空时，置灰相关按钮
    if(num <= 0) {
        pnode.find(".goods_edit").attr("disabled", "disabled").addClass("dis_btn");
    } else {
        pnode.find(".goods_edit").removeAttr("disabled").removeClass("dis_btn");
    }
}

//添加
function detailadd() {
    var brandIds=""
    var brandIdname=""
    if($("#username").val()==""){
        brandIds=""
        brandIdname=""
            brandIdname=""
    }else {
        if(brandId!=""||brandName!=""){
            brandIds=brandId/*jsonobj1*/
            brandIdname=brandName
        }else {
            $.Huimodalalert('品牌不存在！',2000);
            return false;
        }
    }
    var oneCategoryIds=''
    var twoCategoryIds=''
    var threeCategoryIds=''
    if($("#class1").val()!='') {
        oneCategoryIds = oneCategoryId

    }else {
        oneCategoryIds = ''

    }
    if( $("#class2").val()!='') {

        twoCategoryIds = twoCategoryId

    }else {

        twoCategoryIds = ''

    }
    if($("#class3").val()!='') {

        threeCategoryIds = threeCategoryId
    }else {

        threeCategoryIds = ''
    }

    if($("#class1").val()==""&&$("#class2").val()==""&&$("#class3").val()==""){
        $.Huimodalalert(" 一级分类或二级分类或三级分类不可为空",2000);
        return false;
    }

    $.ajax({
        contentType: "application/json;charset=UTF-8",
        url:root.dockingplatform.addPriceInfoRule,
        cache: false,  //禁用缓存
        type: "POST",
        dataType:'json',
        data: JSON.stringify({
            "customerId":customerids,
            "firstCategoryId": oneCategoryIds,
            "secondCategoryId": twoCategoryIds,
            "thirdCategoryId": threeCategoryIds,
            "firstCategoryName":$("#class1").val(),
            "secondCategoryName":$("#class2").val(),
            "thirdCategoryName": $("#class3").val(),
            "brandName": brandIdname/*$("#username").val().trim()*/,
            "brandId":brandIds,
            "currentUserId":JSON.parse(web.readCookie("loginData")).user.user_ID
        }),
        success: function (data) {
            if (data.errorCode==0){
                $.Huimodalalert("添加成功",2000);
                $("#class1").val("")
                $("#class2").val("")
                $("#class3").val("")
                $("#username").val("")
                perceshow();

            }else {
                $.Huimodalalert(data.msg,2000);
            }

        },
        error: function () {
            $.Huimodalalert('失败！',2000);
        }
    })
}

//全选
$(function() {
    //实现全选反选
    $("#pitchAll").on('click', function() {
        $("tbody input:checkbox").prop("checked", $(this).prop('checked'));
    })
    $("tbody input:checkbox").on('click', function() {
        //当选中的长度等于checkbox的长度的时候,就让控制全选反选的checkbox设置为选中,否则就为未选中
        if($("tbody input:checkbox").length === $("tbody input:checked").length) {
            $("#pitchAll").prop("checked", true);
        } else {
            $("#pitchAll").prop("checked", false);
        }
    })
})

//全部取消
function cancleall() {
    var cu = layer.confirm('<span>确认取消全部吗？</span>', {title:'提示',btn: ['确认', '取消']}, function(index){
        cancle3()
        layer.close(cu);
    },function(){
        layer.close(cu);

    });
}
function cancle3() {
    $.ajax({
        url:root.dockingplatform.cleanPriceInfoRule,
        contentType: "application/json;charset=UTF-8",
        cache: false,  //禁用缓存
        type: "POST",
        dataType:'json',
        data: JSON.stringify({
            "customerId":customerids
        }),
        success: function (result) {
            if (result.errorCode==0) {
                $.Huimodalalert('取消成功！',2000);
                perceshow();
            }

        },
        error: function () {
            $.Huimodalalert('失败！',2000);
        }
    });
}
//批量取消
function priceChecked() {
    var spuIdArr=document.getElementsByName('spuId');
    var str=""
    for(var i=0; i < spuIdArr.length;i++){
        if(spuIdArr[i].checked==true){
            str+= spuIdArr[i].value+','
        }
    }
    str = str.substring(0, str.length - 1);
    if(str==''){
        $.Huimodalalert('请选择批量取消的数据！',2000);
        return false;
    }else {
        priceChecked1()
    }
}
function priceChecked1() {
    var cu = layer.confirm('<span>确认取消选中的数据吗？</span>', {title:'提示',btn: ['确认', '取消']}, function(index){
        priceChecked2()
        layer.close(cu);
    },function(){
        layer.close(cu);

    });
}
function priceChecked2(){
    var spuIdArr=document.getElementsByName('spuId');
    var str=""
    for(var i=0; i < spuIdArr.length;i++){
        if(spuIdArr[i].checked==true){
            str+= spuIdArr[i].value+','
        }
    }
    str = str.substring(0, str.length - 1);

    var objArr = [];
    if (str.indexOf(",") != -1) {
        var split = str.split(",");
        for (var i = 0; i < split.length; i++) {
            objArr.push(Number(split[i]));
        }
    } else {
        objArr.push(str);
    }
    $.ajax({
        url:root.dockingplatform.deletePriceInfoRule,
        contentType: "application/json;charset=UTF-8",
        cache: false,  //禁用缓存
        type: "POST",
        dataType:'json',
        data: JSON.stringify({"ids":objArr}),
        success: function (data) {
            if(data.errorCode==0){
                $.Huimodalalert('取消成功！',2000);
                $("#spu_all").attr("checked",false);
                $("#pitchAll").attr("checked",false);
                perceshow();
            }else {
                $.Huimodalalert(data.msg,2000);
            }

        },
        error: function () {
            $.Huimodalalert('失败！',2000);
        }
    })
}
/*var customer_type = sessionStorage.getItem("customer_type");*/
var customertype=""
//修改
function Cloes(modifyPriceWay,id,skucode,el) {
    if($("input[name=radio1]:checked").val()==""||$("input[name=radio1]:checked").val()==undefined){
        $.Huimodalalert('请选择基础价！',2000);
        return false;
    }
    if($(el).parent().find('select').val()==10){
        console.log("qqqqqqqqqqqqq")
        if($(el).parent().find('input').val()>299 || $(el).parent().find('input').val()< 80){
            $.Huimodalalert('折扣率应在80%-299%范围内！',2000);
            setTimeout(function () {
               /* $(el).parent().find('input').val("100")*/
                perceshow()
            }, 1000);
       return false;
        }
    }
    console.log(customerTypes)
    if (customerTypes=="商店"){
        customertype=10
    }else {
        customertype=20
    }
    inputmm=$(el).parent().find('input').val()
    inputid=id
    inputcode=skucode
    modifyPriceWays=$(el).parent().find('select').val()
    console.log($("input[name=radio1]:checked").val())
    var zhekou=""
    if($("#zhekou").val()==""){
        zhekou="100"
    }else {
        zhekou=$("#zhekou").val()
    }
    if($(el).parent().find('input').val()==""){
        $.Huimodalalert('请填写详细信息！',2000);
        return false;
    }
    $.ajax({
        url:root.dockingplatform.updatePriceInfoRule,
        cache: false,  //禁用缓存
        type: "POST",
        dataType:'json',
        contentType: "application/json",
        data: JSON.stringify({

            "customerId": customerids,
            "currentUserId": JSON.parse(web.readCookie("loginData")).user.user_ID,
            "customerPriceUnifyRuleDto": {
                "basePriceType":$("input[name=radio1]:checked").val(),
                "customerUnifyCount":zhekou,
            },
            "customerPriceInfoRuleDtos": [{
                "id": id,
                "modifyPriceWay": $(el).parent().find('select').val(),
                "modifyPriceValue": $(el).parent().find('input').val(),

            }]

        }),
        success: function (data) {
            if(data.errorCode==0){
                $.Huimodalalert('修改成功！',2000);
                perceshow();
            }else {
                inputmsg=data.sub_code
               if (data.sub_code==6 ){
                   updamm(id,el);
               }if (data.sub_code==7 ){
                    updamm(id,el);
                }
            }

        },
        error: function () {
            $.Huimodalalert('失败！',2000);
        }
    })
}
//修改密码弹框
var index=0;
function updamm(id,el) {
    var kop=""
    if(inputmsg==6){
        kop="存在低于成本价的商品"
    }else if(inputmsg==7){
        kop="存在低于成本价80%的商品"
    }
    var cu = layer.confirm('<span>'+kop+",确认修改请输入密码"+'</span><input class="input-text radius" placeholder="请输入密码" type="password" style="padding-left: 10px;" id="remarksr">', {title:'提示',btn: ['确认', '取消']}, function(index){
        fini3(id,el)
        layer.close(cu);
    },function(){
        layer.close(cu);

    });
}
//第二个
function fini3(id,el){
    var remarksr = $("#remarksr").val();
    console.log(remarksr)
    var zhekou=""
    if($("#zhekou").val()==""){
        zhekou="100"
    }else {
        zhekou=$("#zhekou").val()
    }
    $.ajax({
        url:root.dockingplatform.updatePriceInfoRule,
        cache: false,  //禁用缓存
        type: "POST",
        dataType:'json',
        contentType: "application/json",
        data: JSON.stringify({

            "customerId": customerids,
            "currentUserId": JSON.parse(web.readCookie("loginData")).user.user_ID,
            "customerPriceUnifyRuleDto": {
                "basePriceType":$("input[name=radio1]:checked").val(),
                "customerUnifyCount":zhekou,
            },
            "customerPriceInfoRuleDtos": [{
                "id": id,
                "modifyPriceWay": $(el).parent().find('select').val(),
                "modifyPriceValue": $(el).parent().find('input').val(),
                "password":$("#remarksr").val().trim()

            }]

        }),
        success: function (data) {
            if(data.errorCode==0){
                $.Huimodalalert('修改成功！',2000);
                perceshow();
            }else {
                if (data.sub_code==8){
                    $.Huimodalalert('密码输入错误！',2000);
                }
            }




        },
        error: function () {
            $.Huimodalalert('失败！',2000);
        }
    })


    layer.close(index);
}
//删除
function detaildelete(id,pElement) {
    console.log(id);
    $(pElement).removeAttr("onclick");
    if(id==''){
        $.Huimodalalert('请选择批量选择数据！',2000);
        return false;
    }
    var objArr = [];
    if (id.indexOf(",") != -1) {
        var split = id.split(",");
        for (var i = 0; i < split.length; i++) {
            objArr.push(Number(split[i]));
        }
    } else {
        objArr.push(id);
    }

    console.log(JSON.stringify(objArr))
    $.ajax({
        url:root.dockingplatform.deletePriceInfoRule,
        contentType: "application/json;charset=UTF-8",
        cache: false,  //禁用缓存
        type: "POST",
        dataType:'json',
        data: JSON.stringify({"ids":objArr}),
        success: function (data) {
            if(data.errorCode==0){
                $.Huimodalalert('删除成功！',2000);
                $("#spu_all").attr("checked",false);
                perceshow();
            }else {
                $.Huimodalalert(data.msg,2000);
            }

        },
        error: function () {
            $.Huimodalalert('失败！',2000);
        }
    })
}

//查询结果页
function queryresults() {
    if($("#class1").val()==""&&$("#class2").val()==""&&$("#class3").val()==""&&$("#username").val().trim()==""&&$("#spuCode").val().trim()==""&&$("#Code").val().trim()==""&&$("#helpCode").val().trim()==""&&$("#spuName").val().trim()==""){
        $.Huimodalalert('请选择要查询的数据！',2000);
        return false;
    }

    var oneCategoryIds=""
    if($("#class1").val()==""){
        oneCategoryIds=""
    }else {
        oneCategoryIds=oneCategoryId
    }
    var twoCategoryIds=""
    if($("#class2").val()==""){
        twoCategoryIds=""
    }else {
        twoCategoryIds=twoCategoryId
    }
    var threeCategoryIds=""
    if($("#class3").val()==""){
        threeCategoryIds=""
    }else {
        threeCategoryIds=threeCategoryId
    }
    $.ajax({
        url:root.inter.findContractCategoryDiscountByCondition,
        contentType: "application/json;charset=UTF-8",
        cache: false,  //禁用缓存
        type: "POST",
        dataType:'json',
        data: JSON.stringify({
            "pageNum":1,
            "pageSize":20,
            "oneCategoryId":oneCategoryIds,
            "twoCategoryId":twoCategoryIds,
            "threeCategoryId":threeCategoryIds,
            "brand":$("#username").val().trim(),
            "spuCode":$("#spuCode").val().trim(),
            "productName":$("#spuName").val().trim(),
            "skuCode":$("#skuCode").val().trim(),
            "helpCode":$("#helpCode").val().trim(),//助记码
            "productCode":$("#Code").val().trim(),
            "customerCode":getQueryString('customerCode'),
            "contractNum": getQueryString('contractNum'),
        }),
        success: function (result) {
            detaiists(result);
            $('.M-box3').pagination({
                pageCount: result.data.totalPage,
                jump: true,
                coping: true,
                prevContent: '上页',
                nextContent: '下页',
                callback: function (api) {
                    $.ajax({
                        url: root.inter.findContractCategoryDiscountByCondition,
                        contentType: "application/json;charset=UTF-8",
                        ccache: false,  //禁用缓存
                        type: "POST",
                        dataType:'json',
                        data: JSON.stringify({
                            "pageNum":api.getCurrent(),
                            "pageSize":20,
                            "oneCategoryId":oneCategoryId,
                            "twoCategoryId":twoCategoryId,
                            "threeCategoryId":threeCategoryId,
                            "brand":$("#username").val().trim(),
                            "spuCode":$("#spuCode").val().trim(),
                            "productName":$("#spuName").val().trim(),
                            "skuCode":$("#skuCode").val().trim(),
                            "helpCode":$("#helpCode").val().trim(),//助记码
                            "productCode":$("#Code").val().trim(),
                            "customerCode":getQueryString('customerCode'),
                            "contractNum": getQueryString('contractNum'),
                        }),
                        success: function (result) {
                            detaiist(result);
                            $("#spu_all").attr("checked", false);
                        },
                        error: function (XMLHttpRequest, textStatus, errorThrown) {
                            alert(XMLHttpRequest);
                        }
                    });
                }
            });

        },
        error: function () {
            $.Huimodalalert('失败！',2000);
        }
    });
}
//搜索
function ditailquery(title,url) {
    console.log("111111111111111")
    if($("#spuCode").val().trim()!=""||$("#helpCode").val().trim()!=""||$("#spuName").val().trim()!=""||$("#skuCode").val().trim()!=""){
       /* sessionStorage.setItem("threeCategoryId",threeCategoryId);
        sessionStorage.setItem("brandid",jsonobj1);*/
        sessionStorage.setItem("spuCode",$("#spuCode").val().trim());
        sessionStorage.setItem("helpCode",$("#helpCode").val().trim());
        sessionStorage.setItem("spuName",$("#spuName").val().trim());
        sessionStorage.setItem("skuCode",$("#skuCode").val().trim());
        sessionStorage.setItem("customerid2",customerids);

        var index = layer.open({
            type: 2,
            title: title,
            content: url
        });
        layer.full(index);
    }else {
        $.Huimodalalert('请填写详细信息！',2000);
    }



}

//保存
function pircaladd(){
    var zhekou=""
    if($("#zhekou").val()==""){
        zhekou="100"
    }else {
        zhekou=$("#zhekou").val()
    }
    if($("input[name=radio1]:checked").val()==""||$("input[name=radio1]:checked").val()==undefined){
        $.Huimodalalert('请选择基础价！',2000);
        return false;
    }
    if($("#zhekou").val()>299 || $("#zhekou").val()< 80){
        $.Huimodalalert('折扣率应在80%-299%范围内！',2000);
        return false;

    }
    $.ajax({
        url:root.dockingplatform.savePriceRule,
        cache: false,  //禁用缓存
        type: "POST",
        dataType:'json',
        contentType: "application/json",
        data: JSON.stringify({

            "customerId": customerids,
            "currentUserId": JSON.parse(web.readCookie("loginData")).user.user_ID,
            "customerPriceUnifyRuleDto": {
                "basePriceType":$("input[name=radio1]:checked").val(),
                "customerUnifyCount":zhekou,
            },
            "customerPriceInfoRuleDtos": dataall

        }),
        success: function (data) {
            if(data.errorCode==0){
                showmsg("保存成功",6);
                /*$.Huimodalalert('保存成功！',2000);
                var index = parent.layer.getFrameIndex(window.name);
                parent.layer.close(index);*/
            }else {
                $.Huimodalalert(data.msg,2000);
                inputcodes=data.sub_code
                if (data.sub_code==6 ){
                    adddamm();
                }if (data.sub_code==7 ){
                    adddamm();
                }
            }

        },
        error: function () {
            $.Huimodalalert('失败！',2000);
        }
    })
}
//保存密码弹框
var index=0;
function adddamm() {
    var kop=""
    if(inputcodes==6){
        kop="存在低于成本价的商品"
    }else if(inputcodes==7){
        kop="存在低于成本价80%的商品"
    }
    var cu = layer.confirm('<span>'+kop+",确认修改请输入密码"+'</span><input class="input-text radius" placeholder="请输入密码" type="password" style="padding-left: 10px;" id="remarksr">', {title:'提示',btn: ['确认', '取消']}, function(index){
        finiadd()
        layer.close(cu);
    },function(){
        layer.close(cu);

    });
}
//第二个
function finiadd(){
    var remarksr = $("#remarksr").val();
    console.log(remarksr)
    var zhekou=""
    if($("#zhekou").val()==""){
        zhekou="100"
    }else {
        zhekou=$("#zhekou").val()
    }
        $.ajax({
            url:root.dockingplatform.savePriceRule,
            cache: false,  //禁用缓存
            type: "POST",
            dataType:'json',
            contentType: "application/json",
            data: JSON.stringify({

                "customerId": customerids,
                "password":$("#remarksr").val().trim(),
                "currentUserId": JSON.parse(web.readCookie("loginData")).user.user_ID,
                "customerPriceUnifyRuleDto": {
                    "basePriceType":$("input[name=radio1]:checked").val(),
                    "customerUnifyCount":zhekou,
                },
                "customerPriceInfoRuleDtos": dataall

            }),
        success: function (data) {
            if(data.errorCode==0){
                $.Huimodalalert('保存成功！',2000);

                var index = parent.layer.getFrameIndex(window.name);
                parent.layer.close(index);
            }else {
                if (data.sub_code==8){
                    $.Huimodalalert('密码输入错误！',2000);
                }
            }




        },
        error: function () {
            $.Huimodalalert('失败！',2000);
        }
    })


    layer.close(index);
}


$("#zhekou").mouseout(function(){
    if($("#zhekou").val()>299 || $("#zhekou").val()< 80){
        $.Huimodalalert('折扣率应在80%-299%范围内！',2000);
        setTimeout(function () {
            $("#zhekou").val("")
        }, 1000);

    }

})


function upLoadFile() {
    $("#fileUp").trigger('click');
    var click_a = document.getElementById("a");
    var click_b = document.getElementById("b");
    if(click_a.checked){
        sessionStorage.setItem("click_a",1)
    }
    if(click_b.checked){
        sessionStorage.setItem("click_b",1)
    }
    sessionStorage.setItem("zhekoulv",$("#zhekou").val())
}


function putDataToPage() {

    var formData = new FormData();
    formData.append('currentUserId',JSON.parse(web.readCookie("loginData")).user.user_ID);
    formData.append('customerId',customerids);
    formData.append('file', $("#fileUp")[0].files[0]);
    $.ajax({
        url: root.dockingplatform.importProductPriceExcel,
        cache: false,  //禁用缓存
        type: "POST",
        // 告诉jQuery不要去处理发送的数据
        processData: false,
        // 告诉jQuery不要去设置Content-Type请求头
        contentType: false,
        data: formData,
        success: function (data) {

            if(data.errorCode==0){
                $.Huimodalalert('导入成功！',2000);

                setTimeout(function () {
                    location.replace(location.href);
                    //show_click()
                }, 1000);
               /* $("#daoru").trigger('click');
                perceshow()*/


          }else {
                $.Huimodalalert(data.msg,2000);
                setTimeout(function () {
                    location.replace(location.href);

                }, 1000);
                /*$("#daoru").trigger('click');*/

            }
            
        }

    });
}

//下载
$('#downloadProductExcelTemplate').attr('href','https://'+ window.location.host +'/api/admin/abaseservice/downLoadFromUrl?urlStr= https://fsyuncai-file.oss-cn-beijing.aliyuncs.com/common/20190614163005280641.xlsx&fileName=价格设置-导入商品模板')
//导出
function daochu() {
    $('#lkkk').attr('href',root.dockingplatform.exportProductPriceExcel+"?customerId="+customerids);


}

// 提示信息
function showmsg(msg,icon){
    layer.msg(msg, {
        icon:icon,
        time: 1000
    },function(){
        if(icon==6){
            var index = parent.location.reload();
            parent.layer.close(index);
        }
    });
}